/**
 * 通过魔术封包唤醒局域网计算机
 *
 */

/**
 * dgram: 可以创建UDP套接字
 * nodejs 内建模块
 */

const net = require('net');
const udp = require('dgram');

/**
 * 创建魔术封包
 * @param {string} mac 网卡MAC地址
 * @returns {Buffer}
 */
function createMagicPacket(mac) {
    mac = mac.replace(/[^0-9a-fA-F]/g, '');
    if (mac.length !== 12) {
        throw new Error(`Bad MAC address "${mac}"`);
    }
    const bufMac = Buffer.from(mac, 'hex');

    let bufRes = Buffer.alloc(6, 0xff);
    for (let i = 0; i < 16; i++) {
        bufRes = Buffer.concat([bufRes, bufMac]);
    }

    console.log('[long] bufRes: ', '(ff ff ff ff ff ff 16*mac)', bufRes.length)
    return bufRes;
}

/**
 * 通过网络唤醒
 * @param {string} mac 网卡MAC地址
 * @param {object} options 可选项
 * @returns {Promise<boolean>}
 */
function wakeOnLAN(mac, options) {
    options = Object.assign({
        address: '255.255.255.255',
        port: 9 // port: 7
    }, options);

    return new Promise((resolve, reject) => {
        const packet = createMagicPacket(mac);

        console.log('[long] packet: ', packet)
        const socket = udp.createSocket(
            net.isIPv6(options.address) ? 'udp6' : 'udp4'
        );

        socket.on('error', function (err) {
            socket.close();
            reject(err);
        });

        socket.once('listening', function () {
            socket.setBroadcast(true);
        });

        socket.send(packet, 0, packet.length, options.port, options.address, function (err, res) {
                socket.close();
                if (err) {
                    return reject(err);
                }
                resolve(res === packet.length);
            }
        );
    });
}

// const mac = '34:F1:50:42:58:47'
// const DELL_MAC = 'AC:ED:5C:47:CC:CD'
const WOL_TOOLS = {
    wakeOnLAN
}

module.exports = WOL_TOOLS

// wakeOnLAN(mac).then(
//   res => {
//       console.log(res);
//   },
//   err => {
//       console.log('wol', err.message);
//   }
// );
